<template>
  <div class="trend-line-chart">
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts/core'
import { LineChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, GridComponent, LegendComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([
  LineChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  CanvasRenderer
])

const props = defineProps<{
  data: { x: string[]; y: number[] },
  title?: string
}>()

const chartRef = ref<HTMLDivElement | null>(null)
let chartInstance: echarts.ECharts | null = null

const renderChart = () => {
  if (!chartRef.value) return
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value, undefined, { renderer: 'canvas' })
  }
  const option = {
    backgroundColor: 'transparent',
    title: {
      text: props.title || '',
      left: 'center',
      top: 10,
      textStyle: {
        color: '#fff',
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0,0,0,0.7)',
      borderColor: '#2196f3',
      textStyle: { color: '#fff' }
    },
    grid: {
      left: '10%',
      right: 0,
      top: 50,
      bottom: 35
    },
    xAxis: {
      type: 'category',
      data: props.data.x,
      axisLine: { lineStyle: { color: '#4e6e8e' } },
      axisLabel: { color: '#b0c9e0',rotate: 45 }
    },
    yAxis: {
      name:'成材率(%)',
      type: 'value',
      axisLine: { lineStyle: { color: '#4e6e8e' } },
      splitLine: { lineStyle: { color: '#23344a' } },
      axisLabel: { color: '#b0c9e0' }
    },
    series: [
      {
        name: '产量(%)',
        type: 'line',
        data: props.data.y,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          color: '#00eaff',
          width: 3
        },
        itemStyle: {
          color: '#00eaff',
          borderColor: '#fff',
          borderWidth: 2
        },
        areaStyle: {
          color: 'rgba(0,234,255,0.15)'
        }
      }
    ]
  }
  chartInstance.setOption(option)
}

onMounted(() => {
  nextTick(renderChart)
})

watch(() => props.data, renderChart, { deep: true })
</script>

<style scoped>
.trend-line-chart {
  width: 100%;
  height: 260px;
  background: #14233c;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  padding: 10px;
}
.chart {
  width: 100%;
  height: 100%;
}
</style>
